﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic.Security;
using Otgruzka.ServicesClients;
using System.ServiceModel;
using DataTier.Entities;
using DataTier;

namespace Otgruzka.Controls.UserAccount
{
    public partial class RoleEdit : System.Web.UI.UserControl
    {
        public int RoleId
        {
            get
            {
                int returned = 0;
                if ((!string.IsNullOrEmpty(this.hRoleId.Value)))
                {
                    try
                    {
                        returned = Convert.ToInt32(this.hRoleId.Value);
                    }
                    catch (Exception ex)
                    { }
                }
                return returned;
            }
            set
            {
                this.hRoleId.Value = value.ToString();
                BindData();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ErrorMessage.Text = string.Empty;
            if (!IsPostBack)
            {
                BindMenuListData();
                BindStateListData();
                BindWebPageListData();
            }
        }

        protected void cbSelectAllMenus_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbSelectAllMenus.Checked)
                this.listMenu.SelectAll();
            else
                this.listMenu.ClearSelection();
        }
        protected void cbSelectAllStates_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbSelectAllStates.Checked)
                this.listState.SelectAll();
            else
                this.listState.ClearSelection();
        }
        protected void cbSelectAllWebPages_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbSelectAllWebPages.Checked)
                this.listWebPage.SelectAll();
            else
                this.listWebPage.ClearSelection();
        }


        /// <summary>
        /// Заполнение списка пунктов Меню
        /// </summary>
        void BindMenuListData()
        {
            var client = new DictionariesClient();
            try
            {
                //список пунктов Меню
                var list = client.GetMenuList(UserPrincipal.Current.UserId);
                listMenu.DataSource = list;
                listMenu.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        /// <summary>
        /// Заполнение списка Статусов
        /// </summary>
        void BindStateListData()
        {
            var client = new DictionariesClient();
            try
            {
                //список Статусов
                var list = client.GetStateList(UserPrincipal.Current.UserId);
                listState.DataSource = list;
                listState.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        /// <summary>
        /// Заполнение списка страниц системы
        /// </summary>
        void BindWebPageListData()
        {
            var client = new DictionariesClient();
            try
            {
                //список страниц системы
                var list = client.GetWebPageList(UserPrincipal.Current.UserId);
                listWebPage.DataSource = list;
                listWebPage.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }



        /// <summary>
        /// Заполнение формы данными из базы
        /// </summary>
        void BindData()
        {
            ClearForm();
            var client = new DictionariesClient();
            try
            {
                var role = client.GetRoleEntity(UserPrincipal.Current.UserId, RoleId);
                if (role != null)
                {
                    // Заполнение формы данными
                    this.txtName.Text = role.Role.Name;
                    this.chOnlyIts.Checked = role.Role.OnlyIts;
                    this.chModifOtherDocum.Checked = role.Role.ModifOtherDocum;

                    //список пунктов Меню
                    BindMenuListData();
                    listMenu.SelectedValues = (role.Menus != null) ? role.Menus.Select(m => m.Id).ToList() : null;

                    //список Статусов
                    BindStateListData();
                    listState.SelectedValues = (role.States != null) ? role.States.Select(s => s.Id).ToList() : null;
                    
                    //список страниц системы
                    BindWebPageListData();
                    listWebPage.SelectedValues = (role.WebPages != null) ? role.WebPages.Select(p => p.Id).ToList() : null;
                }
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        /// <summary>
        /// Очистка полей формы создания Роли
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNewRole_Click(object sender, EventArgs e)
        {
            RoleId = 0;
        }

        private void ClearForm()
        {
            BindMenuListData();
            BindStateListData();
            BindWebPageListData();

            // Очистка формы данными
            this.txtName.Text = "";
            this.chOnlyIts.Checked = false;
            this.chModifOtherDocum.Checked = false;
        }


        /// <summary>
        /// Сохранение Роли
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveRole_Click(object sender, EventArgs e)
        {
            var role = GetRoleEntity();
            if (role != null)
            {
                var client = new DictionariesClient();
                try
                {
                    int id = client.SaveRoleEntity(UserPrincipal.Current.UserId, role);
                    RoleId = id;
                }
                catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
                {
                    string message = client.GetExceptionDetail(ex);
                    this.ErrorMessage.Text = message;
                }
                catch (System.Exception exp)
                {
                    this.ErrorMessage.Text = exp.Message;
                }
            }
        }


        /// <summary>
        /// Создается объект Роль с информацией о правах пользователя на основании полей ввода формы
        /// </summary>
        /// <returns></returns>
        private RoleEntity GetRoleEntity()
        {
            var role = new RoleEntity()
            {
                Role = new Role()
                        {
                            Id = RoleId,
                            Name = this.txtName.Text,
                            OnlyIts = this.chOnlyIts.Checked,
                            ModifOtherDocum = this.chModifOtherDocum.Checked
                        },
            };

            if (listMenu.SelectedValues != null && listMenu.SelectedValues.Count > 0)
            {
                var menus = listMenu.SelectedValues.Select(m => new DataTier.Menu() { Id = m }).ToList();
                role.Menus = menus;
            }
            if (listState.SelectedValues != null && listState.SelectedValues.Count > 0)
            {
                var states = listState.SelectedValues.Select(s => new State() { Id = s }).ToList();
                role.States = states;
            }
            if (listWebPage.SelectedValues != null && listWebPage.SelectedValues.Count > 0)
            {
                var webPages = listWebPage.SelectedValues.Select(p => new WebPage() { Id = p }).ToList();
                role.WebPages = webPages;
            }

            return role;
        }
    }
}